package com.xinpu.shiro;


import com.xinpu.entity.TCompany;
import com.xinpu.entity.TCompanyUser;
import com.xinpu.entity.TManage;
import com.xinpu.service.ITCompanyService;
import com.xinpu.service.ITCompanyUserService;
import com.xinpu.service.ITManageService;
import com.xinpu.service.TokenService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {


    @Autowired
    private TokenService tokenService;
    @Autowired
    private ITCompanyUserService userService;


    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        try {
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            return simpleAuthorizationInfo;
        } catch (Exception ex) {
            throw new UnauthorizedException("解析无效");
        }
    }

    /**
     * 用户登录授权
     *
     * @param authenticationToken
     * @return
     * @throws Exception
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        String token = (String) authenticationToken.getCredentials();
        //判断token是否有效
        if (!tokenService.valid(token)) {
            throw new UnknownAccountException("授权信息已经过期，请重新登录");
        }
        //判断是否为内部 通信token
        //获取用户编号
        Integer userId = Integer.parseInt(tokenService.getItem(token, "id"));
        if (userId == null || userId <= 0) {
            throw new UnauthenticatedException("请求签名不正确");
        }
        //获取登录用户
        TCompanyUser tCompanyUser = userService.getById(userId);
        if (tCompanyUser == null) {
            throw new UnauthenticatedException("请求授权错误");
        }
        Loginer loginer = new Loginer(tCompanyUser.getId(), tCompanyUser.getPhone(), tCompanyUser.getName(), tCompanyUser.getTenantId());
        return new SimpleAuthenticationInfo(loginer, token, this.getName());
    }
}
